package com.study.netty;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class ServerSocketChannelDemo {


    public static void main(String[] args) throws IOException {
        // 打开 ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        IntBuffer.allocate(5);
        // 绑定端口
        serverSocketChannel.socket().bind(new InetSocketAddress(8080));
        // 打开 Selector
        Selector selector = Selector.open();
        // 注册 ServerSocketChannel 到 Selector
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // 循环处理事件
        while (true) {
            // 非阻塞地等待注册的通道事件发生,不会占用CPU
            selector.select();
//            selector.keys();
//            selector.selectedKeys()

            // 获取发生事件的 SelectionKey 对象集合
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = selectedKeys.iterator();

            // 循环处理这些 SelectionKey
            while (it.hasNext()) {
                SelectionKey key = it.next();
                it.remove();

                // 如果是新连接事件
                if (key.isAcceptable()) {
                    // 获取 ServerSocketChannel 并接受新连接
                    ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = ssc.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector,SelectionKey.OP_READ);
                }
                else if(key.isReadable()){
                    SocketChannel ssc = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(6);
                    int len = ssc.read(buffer);
                    if(len > 0){
                        System.out.println(new String(buffer.array()));
                    }else if(len == -1){
                        // 客户端断开连接,关闭socket
                        ssc.close();
                    }
                }
                // 其他事件处理...
            }
        }
    }

    private void test(){
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        // HeapByteBuffer

        // DirectByteBuffer

    }
}


